<template>
    <view class="page-container">
        <!-- 顶部导航栏 -->
        <NavBar :showBack="true" :userName="userName" :isLoggedIn="!!userName" title="故事编辑" />

        <!-- 内容区域 -->
        <scroll-view scroll-y class="content-area">
            <!-- 故事封面和基本信息 -->
            <view class="story-header">
                <view class="story-cover-large">
                    <view class="empty-banner"></view>
                    <text class="story-tag">{{ storyData.tag }}</text>
                </view>
                <view class="story-header-info">
                    <input class="story-title-input" type="text" v-model="storyData.title" placeholder="请输入故事标题" />
                </view>
            </view>

            <!-- 内容导航 -->
            <view class="content-nav">
                <view class="nav-item" :class="{ active: activeTab === 'personal' }" @click="switchTab('personal')">
                    <text>个人故事</text>
                </view>
                <view class="nav-item" :class="{ active: activeTab === 'fiveQuestions' }"
                    @click="switchTab('fiveQuestions')">
                    <text>五道人生</text>
                </view>
                <!-- <view class="nav-item" :class="{ active: activeTab === 'keyMoments' }" @click="switchTab('keyMoments')">
                    <text>重要时刻</text>
                </view> -->
            </view>

            <!-- 个人故事内容 -->
            <view v-if="activeTab === 'personal'" class="tab-content personal-story">
                <view class="edit-form">
                    <view class="form-item">
                        <text class="form-label">故事内容</text>
                        <textarea class="form-textarea" v-model="storyData.content" placeholder="请输入故事内容" />
                    </view>

                    <view class="form-item">
                        <text class="form-label">故事分类</text>
                        <view class="classification-selector">
                            <view class="classification-option" :class="{ active: storyData.classification === 1 }"
                                @click="storyData.classification = 1">
                                <text>爱与关系</text>
                            </view>
                            <view class="classification-option" :class="{ active: storyData.classification === 2 }"
                                @click="storyData.classification = 2">
                                <text>奋斗与成长</text>
                            </view>
                            <view class="classification-option" :class="{ active: storyData.classification === 3 }"
                                @click="storyData.classification = 3">
                                <text>意义与超越</text>
                            </view>
                        </view>
                    </view>

                    <view class="form-item">
                        <text class="form-label">共享权限</text>
                        <view class="switch-container">
                            <text>{{ storyData.isStorySharable === 0 ? '可共享' : '不可共享' }}</text>
                            <switch :checked="storyData.isStorySharable === 0" @change="toggleStorySharable"
                                color="#46bba0" />
                        </view>
                    </view>

                    <view class="form-item">
                        <text class="form-label">故事标签</text>
                        <view class="tags-container">
                            <view v-for="(tag, index) in storyData.tags" :key="index" class="tag-item">
                                <text class="tag-text">{{ tag }}</text>
                                <text class="tag-delete" @click="removeTag(index)">×</text>
                            </view>
                            <view class="tag-add" @click="showTagInput = true" v-if="!showTagInput">
                                <text>+ 添加标签</text>
                            </view>
                            <view class="tag-input-container" v-if="showTagInput">
                                <input class="tag-input" type="text" v-model="newTag" placeholder="输入标签名称"
                                    @blur="addTag" @confirm="addTag" focus />
                            </view>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 五道人生内容 -->
            <view v-if="activeTab === 'fiveQuestions'" class="tab-content five-questions">
                <view class="edit-form">
                    <view class="form-item">
                        <text class="form-label">共享权限</text>
                        <view class="switch-container">
                            <text>{{ isFimSharable === 0 ? '可共享' : '不可共享' }}</text>
                            <switch :checked="isFimSharable === 0" @change="toggleFimSharable" color="#46bba0" />
                        </view>
                    </view>
                    <view v-for="(question, index) in fiveQuestions" :key="index" class="question-card">
                        <view class="question-header">
                            <text class="question-number"> {{ index + 1 }} 、</text>
                            <text class="question-title">{{ question.title }}</text>
                        </view>
                        <textarea class="question-answer-input" v-model="question.answer"
                            :placeholder="'修改回答'"></textarea>
                    </view>
                </view>
            </view>

            <!-- 重要时刻内容 -->
            <view v-if="activeTab === 'keyMoments'" class="tab-content key-moments">
                <view class="edit-form">
                    <view v-for="(moment, index) in keyMoments" :key="index" class="moment-card">
                        <view class="moment-header">
                            <text class="moment-number">时刻 {{ index + 1 }}</text>
                            <text class="moment-delete" @click="removeMoment(index)">删除</text>
                        </view>
                        <view class="moment-content">
                            <view class="form-item">
                                <text class="form-label">时间</text>
                                <input class="form-input" type="text" v-model="moment.date" placeholder="请输入时间" />
                            </view>
                            <view class="form-item">
                                <text class="form-label">标题</text>
                                <input class="form-input" type="text" v-model="moment.title" placeholder="请输入标题" />
                            </view>
                            <view class="form-item">
                                <text class="form-label">描述</text>
                                <textarea class="form-textarea" v-model="moment.description" placeholder="请输入描述" />
                            </view>
                            <view class="form-item">
                                <text class="form-label">图片</text>
                                <view class="moment-image-container">
                                    <image v-if="moment.image" :src="moment.image" mode="aspectFill"
                                        class="moment-image">
                                    </image>
                                    <view v-else class="moment-image-add" @click="chooseMomentImage(index)">
                                        <text class="add-icon">+</text>
                                        <text class="add-text">添加图片</text>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                    <view class="add-moment" @click="addNewMoment">
                        <text>+ 添加新时刻</text>
                    </view>
                </view>
            </view>

            <!-- 底部操作栏 -->
            <view class="bottom-actions">
                <button class="btn-cancel" @click="goBack">取消</button>
                <button class="btn-save" @click="saveStory">保存</button>
            </view>
        </scroll-view>
    </view>
</template>

<script>
import NavBar from '@/components/NavBar.vue';
import BannerSwiper from '@/components/BannerSwiper.vue';
import { getPersonalStory, savePersonalStory, updatePersonalStory, uploadStoryImage } from '@/api/story.js';

export default {
    components: {
        NavBar,
        BannerSwiper
    },
    data() {
        return {
            activeTab: 'personal',
            userId: '',
            userName: '',
            storyData: {
                title: '',
                content: '',
                tags: [],
                images: [],
                tag: '人生',
                classification: 1, // 默认为"爱与关系"
                isStorySharable: 0 // 默认可共享
            },
            isFimSharable: 0, // 默认可共享
            showTagInput: false,
            newTag: '',
            isEdit: false,
            storyId: null,
            fiveQuestions: [
                {
                    title: '【道谢】想感谢的人们',
                    answer: ''
                },
                {
                    title: '【道歉】倾诉心中歉意',
                    answer: ''
                },
                {
                    title: '【道爱】表达心中的爱',
                    answer: ''
                },
                {
                    title: '【道别】亲口说声再见',
                    answer: ''
                },
                {
                    title: '【道愿】诉说人生遗憾',
                    answer: ''
                }
            ],
            keyMoments: []
        }
    },
    onLoad(options) {
        // 从本地存储获取用户信息
        const userInfo = uni.getStorageSync('userInfo');
        if (userInfo && userInfo.isLoggedIn) {
            this.userName = userInfo.userName;
            this.userId = userInfo.userId || '1001'; // 默认使用1001作为测试ID

            // 如果有传入故事ID，则是编辑模式
            if (options.id) {
                this.isEdit = true;
                this.storyId = options.id;
                this.loadStoryData(options.id);
            } else {
                // 如果没有传入故事ID，则获取用户自己的故事数据
                this.fetchUserStory();
            }
        } else {
            // 未登录状态，跳转到登录页
            uni.showToast({
                title: '请先登录',
                icon: 'none',
                duration: 2000,
                complete: () => {
                    setTimeout(() => {
                        uni.navigateTo({
                            url: '/pages/login/login'
                        });
                    }, 2000);
                }
            });
            return;
        }
    },
    methods: {
        goBack() {
            uni.navigateBack();
        },
        switchTab(tab) {
            this.activeTab = tab;
        },
        // 获取用户自己的故事数据
        fetchUserStory() {
            uni.showLoading({
                title: '加载中...'
            });

            getPersonalStory(this.userId)
                .then(response => {
                    // 检查响应数据结构
                    console.log("获取用户故事数据响应:", response);
                    if (response && response.success && response.data && response.data.length > 0) {
                        const data = response.data[0];
                        console.log("用户故事数据:", data);

                        // 设置为编辑模式并保存故事ID
                        this.isEdit = true;
                        this.storyId = data.id;

                        // 更新故事数据
                        this.storyData = {
                            id: data.id,
                            title: data.storyTitle || '我的人生故事',
                            content: data.storyLife || '',
                            tags: data.storyTags ? data.storyTags.split(',') : [],
                            images: [],
                            tag: data.storyTag || '人生',
                            classification: data.storyClassification || 1,
                            isStorySharable: data.isStorySharable !== undefined ? data.isStorySharable : 0
                        };

                        // 更新五道人生共享权限
                        this.isFimSharable = data.idFimSharable !== undefined ? data.idFimSharable : 0;

                        // 更新五道人生内容
                        this.fiveQuestions[0].answer = data.fimThanks || '';
                        this.fiveQuestions[1].answer = data.fimApology || '';
                        this.fiveQuestions[2].answer = data.fimLove || '';
                        this.fiveQuestions[3].answer = data.fimFarewell || '';
                        this.fiveQuestions[4].answer = data.fimWish || '';

                        // 更新重要时刻数据
                        if (data.keyMoments) {
                            try {
                                this.keyMoments = JSON.parse(data.keyMoments);
                            } catch (e) {
                                console.error('解析重要时刻数据失败:', e);
                                this.keyMoments = [];
                            }
                        }
                    } else {
                        // 用户没有故事数据，使用默认值
                        console.log("用户没有故事数据，使用默认值");
                    }
                })
                .catch(err => {
                    console.error('获取用户故事数据失败:', err);
                    uni.showToast({
                        title: '获取数据失败',
                        icon: 'none'
                    });
                })
                .finally(() => {
                    uni.hideLoading();
                });
        },
        loadStoryData(id) {
            uni.showLoading({
                title: '加载中...'
            });

            getPersonalStory(id)
                .then(response => {
                    // 检查响应数据结构
                    console.log("获取故事数据响应:", response);
                    if (response && response.success && response.data && response.data.length > 0) {
                        const data = response.data[0];
                        console.log("故事数据:", data);

                        // 更新故事数据 - 使用与personalStory.vue相同的字段名
                        this.storyData = {
                            id: data.id || id,
                            title: data.storyTitle || '我的人生故事',
                            content: data.storyLife || '',
                            tags: data.storyTags ? data.storyTags.split(',') : [],
                            images: [],
                            tag: data.storyTag || '人生',
                            classification: data.storyClassification || 1,
                            isStorySharable: data.isStorySharable !== undefined ? data.isStorySharable : 0
                        };

                        // 更新五道人生共享权限
                        this.isFimSharable = data.idFimSharable !== undefined ? data.idFimSharable : 0;

                        // 更新五道人生内容
                        this.fiveQuestions[0].answer = data.fimThanks || '';
                        this.fiveQuestions[1].answer = data.fimApology || '';
                        this.fiveQuestions[2].answer = data.fimLove || '';
                        this.fiveQuestions[3].answer = data.fimFarewell || '';
                        this.fiveQuestions[4].answer = data.fimWish || '';

                        // 更新重要时刻数据
                        if (data.keyMoments) {
                            try {
                                this.keyMoments = JSON.parse(data.keyMoments);
                            } catch (e) {
                                console.error('解析重要时刻数据失败:', e);
                                this.keyMoments = [];
                            }
                        }
                    }
                })
                .catch(err => {
                    console.error('获取故事数据失败:', err);
                    uni.showToast({
                        title: '获取数据失败',
                        icon: 'none'
                    });
                })
                .finally(() => {
                    uni.hideLoading();
                });
        },
        addTag() {
            if (this.newTag.trim()) {
                if (!this.storyData.tags.includes(this.newTag.trim())) {
                    this.storyData.tags.push(this.newTag.trim());
                }
                this.newTag = '';
            }
            this.showTagInput = false;
        },
        removeTag(index) {
            this.storyData.tags.splice(index, 1);
        },

        addNewMoment() {
            this.keyMoments.push({
                date: '',
                title: '',
                description: '',
                image: ''
            });
        },
        removeMoment(index) {
            this.keyMoments.splice(index, 1);
        },
        // 移除图片上传功能，保留方法以避免引用错误
        chooseMomentImage(index) {
            uni.showToast({
                title: '图片上传功能已禁用',
                icon: 'none'
            });
        },
        toggleStorySharable(e) {
            this.storyData.isStorySharable = e.detail.value ? 0 : 1;
        },

        toggleFimSharable(e) {
            this.isFimSharable = e.detail.value ? 0 : 1;
        },

        saveStory() {
            // 表单验证
            if (!this.storyData.title.trim()) {
                uni.showToast({
                    title: '请输入故事标题',
                    icon: 'none'
                });
                return;
            }

            if (this.activeTab === 'personal' && !this.storyData.content.trim()) {
                uni.showToast({
                    title: '请输入故事内容',
                    icon: 'none'
                });
                return;
            }

            // 准备要保存的数据 - 使用与后端API匹配的字段名
            const saveData = {
                userId: this.userId,
                storyTitle: this.storyData.title,
                storyLife: this.storyData.content,
                storyTag: this.storyData.tag,
                storyTags: this.storyData.tags.join(','),
                storyImages: JSON.stringify([]), // 空数组，不需要图片
                fimThanks: this.fiveQuestions[0].answer,
                fimApology: this.fiveQuestions[1].answer,
                fimLove: this.fiveQuestions[2].answer,
                fimFarewell: this.fiveQuestions[3].answer,
                fimWish: this.fiveQuestions[4].answer,
                keyMoments: JSON.stringify([]), // 空数组，不需要重要时刻
                isStorySharable: this.storyData.isStorySharable, // 添加个人故事共享权限
                storyClassification: this.storyData.classification, // 添加故事分类
                idFimSharable: this.isFimSharable // 添加五道人生共享权限
            };

            uni.showLoading({
                title: '保存中...'
            });

            // 根据是否是编辑模式选择保存或更新方法
            const savePromise = this.isEdit
                ? updatePersonalStory(this.storyId, saveData)
                : savePersonalStory(saveData);

            savePromise
                .then(() => {
                    uni.hideLoading();
                    uni.showToast({
                        title: '保存成功',
                        icon: 'success'
                    });

                    setTimeout(() => {
                        uni.navigateBack();
                    }, 1500);
                })
                .catch(err => {
                    uni.hideLoading();
                    console.error('保存故事失败:', err);
                    uni.showToast({
                        title: err || '保存失败',
                        icon: 'none'
                    });
                });
        }
    }
}
</script>

<style>
.page-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background-color: #f8f8f8;
}

.nav-bar {
    display: flex;
    align-items: center;
    padding: 20rpx 30rpx;
    /* background-color: #4a90e2; */
    background: linear-gradient(135deg, #46bba0, #23804b);
    color: #fff;
    position: relative;
}

.back-button {
    padding: 10rpx;
}

.back-icon {
    width: 40rpx;
    height: 40rpx;
}

.page-title {
    flex: 1;
    text-align: center;
    font-size: 36rpx;
    font-weight: bold;
    margin-right: 60rpx;
}

.content-area {
    flex: 1;
    padding: 0;
    padding-bottom: 30rpx;
    height: 84vh;
}

.story-header {
    position: relative;
    margin-bottom: 30rpx;
}

.story-cover-large {
    height: 400rpx;
    background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    position: relative;
    border-radius: 0 0 30rpx 30rpx;
    overflow: hidden;
}

.empty-banner {
    width: 100%;
    height: 100%;
    background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.story-tag {
    position: absolute;
    top: 20rpx;
    left: 20rpx;
    background-color: rgba(0, 0, 0, 0.6);
    color: white;
    padding: 8rpx 16rpx;
    border-radius: 8rpx;
    font-size: 24rpx;
}

.story-header-info {
    padding: 30rpx;
    background-color: white;
    border-radius: 20rpx;
    margin: -50rpx 30rpx 0;
    position: relative;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.story-title-input {
    width: 100%;
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    border: none;
    background: transparent;
    padding: 10rpx 0;
}

.content-nav {
    display: flex;
    justify-content: space-around;
    background-color: white;
    padding: 20rpx 0;
    margin: 0 30rpx 30rpx;
    border-radius: 15rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.nav-item {
    padding: 15rpx 30rpx;
    border-radius: 10rpx;
    transition: all 0.3s;
}

.nav-item.active {
    background-color: #f0f0f0;
    font-weight: bold;
    color: #333;
}

.tab-content {
    padding: 0 30rpx;
}

.edit-form {
    background-color: white;
    padding: 30rpx;
    border-radius: 15rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.form-item {
    margin-bottom: 20rpx;
}

.form-label {
    display: block;
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
    font-weight: bold;
}

.form-input {
    width: 100%;
    height: 80rpx;
    border: 1px solid #e0e0e0;
    border-radius: 8rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
    box-sizing: border-box;
}

.form-textarea {
    width: 100%;
    height: 300rpx;
    background-color: #f9f9f9;
    border-radius: 10rpx;
    padding: 20rpx;
    box-sizing: border-box;
    font-size: 28rpx;
    margin-top: 10rpx;
}

.tags-container {
    display: flex;
    flex-wrap: wrap;
    margin-top: 10rpx;
}

.classification-selector {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
    margin-top: 10rpx;
}

.classification-option {
    padding: 15rpx 30rpx;
    background-color: #f0f0f0;
    border-radius: 30rpx;
    font-size: 28rpx;
    color: #666;
    transition: all 0.3s;
}

.classification-option.active {
    background-color: #46bba0;
    color: white;
}

.switch-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 10rpx;
    padding: 15rpx 20rpx;
    background-color: #f9f9f9;
    border-radius: 10rpx;
}

.tag-item {
    display: flex;
    align-items: center;
    background-color: rgba(74, 144, 226, 0.1);
    padding: 8rpx 15rpx;
    border-radius: 30rpx;
}

.tag-text {
    font-size: 24rpx;
    color: #2d9062;
}

.tag-delete {
    font-size: 24rpx;
    color: #2d9062;
    margin-left: 10rpx;
    font-weight: bold;
}

.tag-add {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 8rpx 15rpx;
    border: 1px dashed #2d9062;
    border-radius: 30rpx;
}

.tag-add text {
    font-size: 24rpx;
    color: #2d9062;
}

.tag-input-container {
    flex: 1;
    min-width: 200rpx;
}

.tag-input {
    height: 60rpx;
    border: 1px solid #2d9062;
    border-radius: 30rpx;
    padding: 0 15rpx;
    font-size: 24rpx;
}

.image-uploader {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
}

.image-item {
    position: relative;
    width: 200rpx;
    height: 200rpx;
}

.uploaded-image {
    width: 100%;
    height: 100%;
    border-radius: 8rpx;
}

.image-delete {
    position: absolute;
    top: -15rpx;
    right: -15rpx;
    width: 40rpx;
    height: 40rpx;
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24rpx;
}

.image-add {
    width: 200rpx;
    height: 200rpx;
    border: 1px dashed #ccc;
    border-radius: 8rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.add-icon {
    font-size: 60rpx;
    color: #ccc;
    margin-bottom: 10rpx;
}

.add-text {
    font-size: 24rpx;
    color: #999;
}

.form-actions {
    display: flex;
    justify-content: space-between;
    margin-top: 40rpx;
}

.btn-cancel,
.btn-save {
    width: 45%;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    border-radius: 40rpx;
    font-size: 28rpx;
}

.btn-cancel {
    background-color: #f5f5f5;
    color: #2d9062;
    border: 3rpx solid #2d9062;
    margin-bottom: 20rpx;
}

.btn-save {
    background-color: #2d9062;
    color: #fff;
}
</style>